package com.lin.manager.sms.strategy;

import cn.hutool.core.lang.Validator;
import com.lin.manager.sms.enums.PlatformEnum;
import com.lin.manager.sms.enums.SendEnum;
import com.lin.manager.sms.ex.CustomSendException;
import com.lin.manager.sms.factory.SmsFactory;
import com.lin.manager.sms.model.dto.SmsDTO;

import java.util.List;
import java.util.Objects;
import java.util.StringJoiner;

/**
 * @author linjiang
 * @date 2024/8/14
 * @fn 短信发送服务（策略模式 + 工厂模式）
 * 1.创建短信工厂
 * 2.从工厂中获取短信服务
 * 3.调用短信服务发送短信
 */
public class SmsStrategy implements SendStrategy<SmsDTO> {
    SmsFactory factory;

    public SmsStrategy(SmsFactory factory) {
        this.factory = factory;
    }

    @Override
    public Boolean send(SmsDTO send) {
        handleParam(send);
        return factory.getSendStrategy().send(send);
    }

    @Override
    public PlatformEnum getPlatform() {
        return null;
    }

    private void handleParam(SmsDTO send) {
        checkPhoneNum(send.getPhoneNums());
    }

    /**
     * 校验手机号
     *
     * @param phoneNums
     */
    private void checkPhoneNum(List<String> phoneNums) {
        if (Objects.isNull(phoneNums)) {
            throw new CustomSendException(SendEnum.SEND_PHONE_NUM_ZERO);
        }

        if (phoneNums.size() > 100) {
            throw new CustomSendException(SendEnum.SEND_PHONE_NUM_HUNDRED);
        }

        // 校验所有的手机号是否是正确格式
        StringJoiner joiner = new StringJoiner(",");
        boolean bool = phoneNums.stream().allMatch(var -> {
            boolean isMobile = Validator.isMobile(var);
            if (!isMobile) {
                joiner.add(var);
            }
            return isMobile;
        });

        if (!bool) {
            throw new CustomSendException(SendEnum.SEND_FAIl.getCode(), String.format("手机号格式错误：【%s】", joiner));
        }
    }
}
